package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.contract.SupplyContract;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SupplyTaskHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;
    @Override
    public void process(String jsonMsg) throws IOException {
        //1.解析协议内容
        SupplyContract contract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        if (contract == null || StringUtils.isEmpty(contract.getSupplyData())) return;
        //2.找出被指派人
        VmVO vmInfo = vmService.getVMInfo(contract.getInnerCode());
        try {
            int leastUserId = taskService.getLeastUser(vmInfo.getRegionId(), false);
            //3.创建补货工单
            TaskViewModel model = new TaskViewModel();
            model.setDesc("补货工单");
            model.setInnerCode(contract.getInnerCode());
            model.setCreateType(0);
            model.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            model.setUserId(leastUserId);
            model.setAssignorId(-1);
            List<TaskDetailsViewModel> list = contract.getSupplyData().stream().map(s -> {
                TaskDetailsViewModel viewModel = new TaskDetailsViewModel();
                viewModel.setSkuId(s.getSkuId());
                viewModel.setChannelCode(s.getChannelId());
                viewModel.setSkuImage(s.getSkuImage());
                viewModel.setSkuName(s.getSkuName());
                viewModel.setExpectCapacity(s.getCapacity());
                return viewModel;
            }).collect(Collectors.toList());
            model.setDetails(list);
            taskService.addTask(model);
        } catch (LoginException e) {
            log.info("创建自动补货工单出错"+e.getMessage());
        }

    }
}
